/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.qidisoft.edu.hzjt.constants.Constant;

/**
 * 
 * @author hxq
 * @version $Id: DynamicDownFileServlet.java, v 0.1 2018年12月7日 下午4:50:52 hxq Exp $
 */
public class DynamicDownFileServlet extends HttpServlet {

  /**  */
  private static final long serialVersionUID = 1L;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 设置服务器输出的编码为UTF-8
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String filename = request.getParameter("filename");
    String path = request.getParameter("filepath");
    String contentType = request.getParameter("contentType");
    String rootPath = Constant.UPLOADPATH;
    if (filename != null && filename != "" && path != null && path != "") {
      String uploadPath = rootPath + "/" + path;
      File f = new File(uploadPath);
      BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
      byte[] buf = new byte[1024];
      int len = 0;
      response.reset();
      filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
      response.setContentType(contentType + ";charset=UTF-8");
      response.setHeader("Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "ISO-8859-1"));
      OutputStream out = response.getOutputStream();
      while ((len = br.read(buf)) > 0)
        out.write(buf, 0, len);
      br.close();
      out.close();
    }
  }
}
